package com.jhgsys.internal.contractor.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.contractor.dto.BaseContractorTeamDto;
import com.jhgsys.internal.contractor.entity.BaseContractor;
import com.jhgsys.internal.contractor.entity.BaseContractorTeam;
import com.jhgsys.internal.contractor.service.IBaseContractorService;
import com.jhgsys.internal.contractor.service.IBaseContractorTeamService;
import com.jhgsys.internal.system.entity.Tenant;
import com.jhgsys.internal.system.entity.User;
import com.jhgsys.internal.system.service.ITenantService;
import com.jhgsys.internal.system.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 承包队设置 Controller
 *
 * @author admin
 * @date 2024-07-29 14:19:05
 */
@Slf4j
@Validated
@Controller
public class BaseContractorTeamController extends BaseController {

    @Autowired
    private IBaseContractorTeamService baseContractorTeamService;

    @Autowired
    private IBaseContractorService contractorService;

    @Autowired
    private ITenantService tenantService;

    @Autowired
    private IUserService userService;


    @GetMapping(FebsConstant.VIEW_PREFIX + "baseContractorTeam/add")
    @RequiresPermissions("baseContractorTeam:add")
    public String baseContractorTeamAdd(){
        return FebsUtil.view("contractor/baseContractorTeam/baseContractorTeamEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "baseContractorTeam/update/{baseContractorTeamId}")
    @RequiresPermissions("baseContractorTeam:update")
    public String baseContractorTeamUpdate(Model model, @PathVariable("baseContractorTeamId") String baseContractorTeamId){
        BaseContractorTeamDto dto = this.baseContractorTeamService.findBaseContractorTeamById(baseContractorTeamId);
        if(ObjectUtils.isNotEmpty(dto)){
            BaseContractor contractor = contractorService.findBaseContractorById(dto.getContractorId());
            if(ObjectUtils.isNotEmpty(contractor)){
                dto.setContractorName(contractor.getContractorName());
            }

            Tenant tenant = tenantService.findTenantByTenantId(dto.getTenantId());
            if(ObjectUtils.isNotEmpty(tenant)){
                dto.setTenantName(tenant.getTenantName());
            }
        }

        model.addAttribute("baseContractorTeam", dto);
        return FebsUtil.view("contractor/baseContractorTeam/baseContractorTeamEdit");
    }

    /**
     * 查询（所有）
     * @author admin
     * @date 2024-07-29 14:19:05
     */
    @GetMapping("baseContractorTeam")
    @ResponseBody
    @RequiresPermissions("baseContractorTeam:view")
    public FebsResponse getAllBaseContractorTeams(BaseContractorTeam baseContractorTeam) {
        return new FebsResponse().success().data(baseContractorTeamService.findBaseContractorTeams(baseContractorTeam));
    }

    /**
     * 查询（分页）
     * @author admin
     * @date 2024-07-29 14:19:05
     */
    @GetMapping("baseContractorTeam/list")
    @ResponseBody
    @RequiresPermissions("baseContractorTeam:view")
    public FebsResponse baseContractorTeamList(QueryRequest request, BaseContractorTeam baseContractorTeam) {
        //默认查询为空
        baseContractorTeam.setContractorId("#");
        Map<String, Object> dataTable = getDataTable(this.baseContractorTeamService.findBaseContractorTeams(request, baseContractorTeam));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 查询（分页）
     * @author admin
     * @date 2024-07-29 14:19:05
     */
    @GetMapping("baseContractorTeam/listByContractorId")
    @ResponseBody
    @RequiresPermissions("baseContractorTeam:view")
    public FebsResponse baseContractorTeamListByContractorId(QueryRequest request, BaseContractorTeam baseContractorTeam) {
        if(!hasHeadCompanyRole() && StringUtils.isBlank(baseContractorTeam.getTenantId())){
            baseContractorTeam.setTenantId(getCurrentTenantId());
        }
        IPage<BaseContractorTeamDto> page = this.baseContractorTeamService.findBaseContractorTeams(request, baseContractorTeam);

        Map<String, Object> dataTable = getDataTable(page);
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 新增 BaseContractorTeam
     * @author admin
     * @date 2024-07-29 14:19:05
     */
    @Log("新增BaseContractorTeam")
    @PostMapping("baseContractorTeam")
    @ResponseBody
    @RequiresPermissions("baseContractorTeam:add")
    public FebsResponse addBaseContractorTeam(@RequestBody BaseContractorTeamDto baseContractorTeam) throws FebsException {
        try {
            if(StringUtils.isBlank(baseContractorTeam.getTenantId())){
                if(hasHeadCompanyRole()){
                    return new FebsResponse().fail().message("所属公司不能为空！");
                }else {
                    baseContractorTeam.setTenantId(getCurrentTenantId());
                }

            }
            if(StringUtils.isBlank(baseContractorTeam.getContractorId())){
                return new FebsResponse().fail().message("承包商编号不能为空！");
            }
            if(StringUtils.isBlank(baseContractorTeam.getTeamName())){
                return new FebsResponse().fail().message("承包队名称不能为空！");
            }
            if(StringUtils.isBlank(baseContractorTeam.getConstructionDeptId())){
                return new FebsResponse().fail().message("实施部门名称不能为空！");
            }

            baseContractorTeam.setCreatedBy(getCurrentUser().getUserName());
            this.baseContractorTeamService.createBaseContractorTeam(baseContractorTeam);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增BaseContractorTeam失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 逻辑删除 BaseContractorTeam
     * @author admin
     * @date 2024-07-29 14:19:05
     */
    @Log("逻辑删除BaseContractorTeam")
    @GetMapping("baseContractorTeam/delete/{baseContractorTeamId}")
    @ResponseBody
    @RequiresPermissions("baseContractorTeam:delete")
    public FebsResponse deleteBaseContractorTeam(@PathVariable("baseContractorTeamId") String baseContractorTeamId) throws FebsException {
        try {
            BaseContractorTeam baseContractorTeam = new BaseContractorTeam();
            baseContractorTeam.setDeletedBy(getCurrentUser().getUserName());
            baseContractorTeam.setDeletedTime(new Date());
            baseContractorTeam.setDeletedFlg("1");
            baseContractorTeam.setContractorTeamId(baseContractorTeamId);
            this.baseContractorTeamService.updateBaseContractorTeamDeletedFlg(baseContractorTeam);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除BaseContractorTeam失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }



    /**
     * 修改 BaseContractorTeam
     * @author admin
     * @date 2024-07-29 14:19:05
     */
    @Log("修改BaseContractorTeam")
    @PostMapping("baseContractorTeam/update")
    @ResponseBody
    @RequiresPermissions("baseContractorTeam:update")
    public FebsResponse updateBaseContractorTeam(@RequestBody BaseContractorTeamDto baseContractorTeam) throws FebsException {
        try {
            if(StringUtils.isBlank(baseContractorTeam.getTenantId())){
                return new FebsResponse().fail().message("租户ID不能为空！");
            }
            if(StringUtils.isBlank(baseContractorTeam.getContractorId())){
                return new FebsResponse().fail().message("承包商Id不能为空！");
            }
            if(StringUtils.isBlank(baseContractorTeam.getTeamName())){
                return new FebsResponse().fail().message("承包队名称不能为空！");
            }
            if(StringUtils.isBlank(baseContractorTeam.getConstructionDeptId())){
                return new FebsResponse().fail().message("实施部门名称不能为空！");
            }
            baseContractorTeam.setUpdatedBy(getCurrentUser().getUserName());
            this.baseContractorTeamService.updateBaseContractorTeam(baseContractorTeam);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改BaseContractorTeam失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }


    /**
     * 查询（分页）
     * @author admin
     * @date 2024-07-29 14:19:05
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "baseContractorTeam/detail/{baseContractorTeamId}")
    @RequiresPermissions("baseContractorTeam:view")
    public String findByTeamName(Model model,@PathVariable("baseContractorTeamId") String baseContractorTeamId) {
        BaseContractorTeamDto dto = this.baseContractorTeamService.findBaseContractorTeamById(baseContractorTeamId);
        if(ObjectUtils.isNotEmpty(dto)){
            BaseContractor contractor = contractorService.findBaseContractorById(dto.getContractorId());
            if(ObjectUtils.isNotEmpty(contractor)){
                dto.setContractorName(contractor.getContractorName());
            }

            Tenant tenant = tenantService.findTenantByTenantId(dto.getTenantId());
            if(ObjectUtils.isNotEmpty(tenant)){
                dto.setTenantName(tenant.getTenantName());
            }
            User userParma = new User();
            userParma.setTenantId(dto.getTenantId());
            userParma.setContractorId(dto.getContractorId());
            userParma.setContractorTeamId(dto.getContractorTeamId());

            List<User> userList =  userService.findUserList(userParma);
            dto.setTeamUserList(userList);
        }

        model.addAttribute("contractorTeam", dto);
        return FebsUtil.view("contractor/baseContractorTeam/baeContractorTeamDetail");
    }

    /**
     * 修改承包商状态
     * @param baseContractorTeam
     * @return
     * @throws FebsException
     */
    @Log("修改承包商状态")
    @PostMapping("baseContractorTeam/updateContractorTeamStatus")
    @ResponseBody
    @RequiresPermissions(value={"baseContractorTeam:update"},logical= Logical.OR)
    public FebsResponse updateContractorTeamStatus(BaseContractorTeam baseContractorTeam) throws FebsException {
        try {
            if(StringUtils.isBlank(baseContractorTeam.getContractorTeamId())){
                return new FebsResponse().fail().message("承包队Id不能为空！");
            }
            if(StringUtils.isBlank(baseContractorTeam.getStatus())){
                return new FebsResponse().fail().message("承包队状态不能为空！");
            }
            baseContractorTeam.setUpdatedBy(getCurrentUser().getUserName());
            baseContractorTeam.setUpdatedTime(new Date());

            this.baseContractorTeamService.updateById(baseContractorTeam);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改岗位状态失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }



//    /**
//     * 导出 BaseContractorTeam的excel
//     * @author admin
//     * @date 2024-07-29 14:19:05
//     */
//    @PostMapping("baseContractorTeam/excel")
//    @ResponseBody
//    @RequiresPermissions("baseContractorTeam:export")
//    public void export(QueryRequest queryRequest, BaseContractorTeam baseContractorTeam, HttpServletResponse response) throws FebsException {
//        try {
//            List<BaseContractorTeamDto> baseContractorTeams = this.baseContractorTeamService.findBaseContractorTeams(queryRequest, baseContractorTeam).getRecords();
//            ExcelKit.$Export(BaseContractorTeam.class, response).downXlsx(baseContractorTeams, false);
//        } catch (Exception e) {
//            String message = "导出Excel失败";
//            log.error(message, e);
//            throw new FebsException(message);
//        }
//    }
}
